package com.itheima.CSM_preX.aabService;

import com.itheima.CSM_preX.aabService.Serv.OrderServ;
import com.itheima.CSM_preX.aacMapper.OrderMapper;
import com.itheima.common.utils.ValidateCodeUtils;
import com.itheima.pojo.DTO.DTOoSubmit;
import com.itheima.pojo.Entity.Member;
import com.itheima.pojo.Entity.Order;
import com.itheima.pojo.VO.VOoFBI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Service
public class OrderImpl implements OrderServ {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public VOoFBI findById(Integer id) {
        Order kk = orderMapper.findById(id);
        VOoFBI vooFBI = new VOoFBI();
        vooFBI.setOrderType(kk.getOrderType());
        vooFBI.setSetmeal(String.valueOf(kk.getSetmealId()));
        LocalDate ddate = kk.getOrderDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        vooFBI.setOrderDate(ddate);
        Order k = orderMapper.findById(id);
        String name = orderMapper.getNameById(k.getMemberId());
        vooFBI.setMember(name);

        return vooFBI;
    }

    @Override
    public Integer submitOrder(DTOoSubmit kk) {
        //验证码检测
        String code = (String) redisTemplate.opsForValue().get(kk.getTelephone());
        if(!code.equals(kk.getValidateCode())){
            return -1;
        }

        Member member = new Member();
        member.setIdCard(kk.getIdCard());
        member.setName(kk.getName());
        member.setSex(kk.getSex()==1?"男":"女");
        member.setPhoneNumber(kk.getTelephone());
        member.setFileNumber(ValidateCodeUtils.generateValidateCode(4).toString());
        //在不在？
        Member mm = orderMapper.findByMember(member);
        if(mm==null){
            orderMapper.addMember(member);
            mm = member;
        }

        Order order = new Order();
        order.setMemberId(mm.getId());
        Date date = Date.from(kk.getOrderDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
        order.setOrderDate(date);
        order.setOrderType("微信预约");
        order.setOrderStatus("否");
        int setmealId = kk.getSetmealId();
        order.setSetmealId(setmealId);
        orderMapper.addOrder(order);
        return order.getId();
    }
}
